import { useEffect, useMemo } from 'react';
import { UploadFormCommon } from '@/components/UploadForm';
import { getTenantID, splitFileUrl, downloadTemplate, getFileNameNotType, getSelectDataCommon, removeDateHmsStr, getSelectDataMapList } from '@/utils';
import { ILoadMapTypeAll } from '@/common';
import { useDescriptionsType } from '@/components/DescriptionsType';
import { RegularExpression } from '@/common/constVariable';
import { Tooltip, TreeSelect, Select, message, Input, Button } from 'antd';
import MyIcon from '@/components/MyIcon';
import { UpdateMaterielView } from './UpdateMaterielView';
import { handleNotPostion } from '@/pages/ContractController/ContractManage/mconfig';
import { UpdateContractView } from './UpdateContractView';
import { findObjectById } from '@/utils/findObjectById';
import { TagSelectNew as TagSelect } from '@/components/TagSelectNew';
import moment from 'moment';
import { getBaseUrl } from '@/services/urlconst';
import { readReadShowFileService } from '@/services/BaseLayout';
import { EyeOutlined } from '@ant-design/icons';

const getUpdateConfig = ({
  pageType,
  record,
  openMaterialModalStatus,
  loadMapInfo,
  mapLoading,
  handleSelectContract,
  contractForm,
  curRes,
  changeGetUser,
  getFlowOrgList,
  getFlowOrgTreeLoading,
  getUserList,
  getUserLoading,
  getSelectUserInfo,
}) => {
  /**资产分类数据字典*/
  const materialTypeMapList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`], 'name', 'id', true);
  /** 折旧方法列表 */
  const depreciateTypeList = getSelectDataCommon(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}`], 'name', 'id');
  /** 资产存放区域类型 */
  const locationList = getSelectDataMapList(loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_AREA}`], 'name', 'id', true);

  /** 表单数据 */

  /** 轻阅读预览 */
  const { readReadShowFileRun } = readReadShowFileService();

  /**轻阅读预览 */
  const onOpenReadOfdWord = (fieldUrl: string) => {
    readReadShowFileRun({ fieldPath: `${getBaseUrl()}${fieldUrl}` });
  };

  useEffect(() => {
    // 回填表单
    contractForm?.setFieldsValue({
      ...record,
      createTime: moment(record?.createTime),
    });
  }, []);

  const disabled: boolean = pageType === 'detail';

  /** 表单配置 */
  const [config, methods] = useDescriptionsType({
    labelWidth: 190,
    basicForm: contractForm,
    name: 'accept-addAndEdit',
    schemas: [
      {
        key: 'accept-basic',
        title: '基本信息',
        fieldChildren: [
          {
            label: '申请日期',
            field: 'createTime',
            component: 'DatePicker',
            placeholder: '请选择申请日期',
            disabled: disabled,
            required: true,
            disabledDate: (current) => {
              return current && current > moment(new Date(), 'YYYY-MM-DD');
            },
          },
          {
            field: `applyCode`,
            label: `流水单号`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            // required: true,
          },
          {
            field: `createrName`,
            label: `申请人`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `createPhone`,
            label: `联系电话`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `createDepartmentName`,
            label: `申请部门/单位`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `createPositionName`,
            label: `职务岗位`,
            component: 'Input',
            // required: true,
            placeholder: '自动带出',
            disabled: true,
          },
          {
            field: `applyTitle`,
            label: `事项名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            required: !disabled,
            colSpan: 0,
          },
          {
            field: `assetName`,
            label: `资产名称`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            required: !disabled,
          },
          {
            field: `usedType`,
            label: `资产用途`,
            disabled: true,
            component: 'Render',
            required: true,
            render: (text) => {
              if (disabled) {
                return <span>{record.usedTypeName ? record.usedTypeName.split('||')[0] : '--'}</span>;
              } else {
                return (
                  <Select
                    loading={mapLoading}
                    options={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_USED}`]}
                    disabled={true}
                    placeholder="请选择"
                    fieldNames={{
                      label: 'name',
                      value: 'id',
                    }}
                  />
                );
              }
            },
          },
          {
            field: `assetClass`,
            label: `资产分类`,
            disabled: disabled,
            component: 'Render',
            required: !disabled,
            render: (text) => {
              if (disabled) {
                return <span>{record?.assetClassName ? record?.assetClassName.split('||')[0] : '--'}</span>;
              } else {
                return (
                  <TreeSelect
                    loading={mapLoading}
                    placeholder="请选择"
                    treeData={materialTypeMapList}
                    disabled={disabled}
                    showArrow={!disabled}
                    fieldNames={{
                      label: 'name',
                      value: 'id',
                      children: 'children',
                    }}
                    showSearch={true}
                    treeNodeFilterProp={'name'}
                    allowClear={true}
                    onSelect={(value: string | number, node: any) => {
                      contractForm.setFieldValue('assetClassCode', node?.shortCode);
                      if (node?.remark) {
                        contractForm.setFieldValue('durableYears', node?.remark);
                      }
                      // let obj = findObjectById(value, loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_TYPE}`], 'id');
                    }}
                  />
                );
              }
            },
          },
          {
            field: `assetClassCode`,
            label: `资产分类编码`,
            component: 'Input',
            disabled: true,
            placeholder: '自动带出',
            required: false,
          },
          {
            field: `paramsInfo`,
            label: `规格型号`,
            component: 'Input',
            disabled: disabled,
            required: !disabled,
            placeholder: '请输入',
          },
          {
            field: `unitOfMeasurement`,
            label: `计量单位`,
            disabled: disabled,
            component: 'Render',
            required: !disabled,
            render: (text) => {
              if (disabled) {
                return <span>{record?.unitOfMeasurementName ? record?.unitOfMeasurementName.split('||')[0] : '--'}</span>;
              } else {
                return (
                  <Select
                    loading={mapLoading}
                    options={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.MATERIAL_MIDI}`]}
                    disabled={disabled}
                    placeholder="请选择"
                    fieldNames={{
                      label: 'name',
                      value: 'id',
                    }}
                  />
                );
              }
            },
          },
          {
            field: `assetOldPrice`,
            label: `资产原值`,
            component: 'InputNumber',
            placeholder: '自动带出',
            disabled: true,
            initialValue: 0.0,
            required: false,
            contentAfter: '元',
          },
          {
            field: `unitPrice`,
            label: `参考价值`,
            component: 'InputNumber',
            placeholder: '请输入',
            disabled: disabled,
            contentAfter: '元',
            min: 0,
            required: !disabled,
          },
          {
            field: `depreciateType`,
            label: `折旧方式`,
            disabled: disabled,
            component: 'Render',
            // required: !disabled ,
            render: (text) => {
              if (disabled) {
                return <span>{record?.depreciateTypeName ? record?.depreciateTypeName.split('||')[0] : '--'}</span>;
              } else {
                return (
                  <TagSelect
                    colSpan={24}
                    formLabel={''}
                    formName={'depreciateType'}
                    defalultKeys={text ? text : `${getTenantID()}${ILoadMapTypeAll.AVERAGE_LIFE_METHOD}1000`}
                    radioDisabled={disabled}
                    radioList={depreciateTypeList}
                  />
                );
              }
            },
          },
          {
            field: `durableYears`,
            label: `使用期限`,
            component: 'InputNumber',
            placeholder: '请输入',
            disabled: disabled,
            required: !disabled,
            min: 0,
            contentAfter: '月',
            pattern: RegularExpression?.number,
            patternMsg: '请输入整数',
          },
          // {
          //   field: `sourceType`,
          //   label: `资产来源`,
          //   disabled: true,
          //   component: 'Render',
          //   required: false,
          //   render: (text) => {
          //     if (disabled) {
          //       return <span>{record.sourceTypeName ? record.sourceTypeName.split('||')[0] : '--'}</span>;
          //     } else {
          //       return (
          //         <Select
          //           loading={mapLoading}
          //           options={loadMapInfo?.[`${getTenantID()}${ILoadMapTypeAll.ASSET_SOURCE_TYPE}`]}
          //           disabled={true}
          //           placeholder="请选择"
          //           fieldNames={{
          //             label: 'name',
          //             value: 'id',
          //           }}
          //         />
          //       );
          //     }
          //   },
          // },
          // {
          //   field: `brandType`,
          //   label: `资产品牌`,
          //   component: 'Input',
          //   disabled: true,
          //   required: false,
          //   placeholder: '自动带出',
          // },
          // {
          //   field: `quantityOrArea`,
          //   label: `资产数量`,
          //   component: 'InputNumber',
          //   placeholder: '请输入',
          //   disabled: true,
          //   required: true,
          //   min: 0,
          //   // contentAfter: '元',
          //   pattern: RegularExpression?.number,
          //   patternMsg: '请输入整数',
          // },
          {
            field: `useDepartmentID`,
            label: `使用部门`,
            disabled: disabled,
            component: 'Render',
            required: !disabled,
            render: (text) => {
              if (disabled) {
                return <span>{record?.useDepartmentName ? record?.useDepartmentName.split('||')[0] : '--'}</span>;
              } else {
                return (
                  <TreeSelect
                    loading={getFlowOrgTreeLoading}
                    placeholder="请选择"
                    treeData={handleNotPostion(getFlowOrgList)}
                    disabled={pageType == 'detail' ? true : false}
                    showArrow={pageType == 'detail' ? false : true}
                    fieldNames={{
                      label: 'title',
                      value: 'id',
                      children: 'children',
                    }}
                    showSearch={true}
                    treeNodeFilterProp={'text'}
                    allowClear={true}
                    onChange={(value: string | number) => {
                      changeGetUser(value);
                    }}
                  />
                );
              }
            },
          },
          {
            field: `userID`,
            label: `使用人`,
            disabled: disabled,
            component: 'Render',
            required: !disabled,
            render: (text) => {
              if (disabled) {
                return <span>{record?.userName ? record?.userName.split('||')[0] : '--'}</span>;
              } else {
                return (
                  <Select
                    loading={getUserLoading}
                    options={getUserList}
                    disabled={disabled}
                    placeholder="请选择"
                    fieldNames={{
                      label: 'realName',
                      value: 'id',
                    }}
                    onChange={(value: number | string, option: any) => {
                      getSelectUserInfo(value, option);
                    }}
                  />
                );
              }
            },
          },
          {
            field: `location`,
            label: `存放区域`,
            component: 'Render',
            required: !disabled,
            render: (text: any) => {
              if (disabled) {
                return <span>{record?.locationName ? record?.locationName.split('||')[0] : '--'}</span>;
              } else {
                return (
                  <TreeSelect
                    loading={mapLoading}
                    placeholder="请选择"
                    treeData={locationList}
                    disabled={disabled}
                    showArrow={disabled}
                    fieldNames={{
                      label: 'name',
                      value: 'id',
                      children: 'children',
                    }}
                    showSearch={true}
                    treeNodeFilterProp={'name'}
                    allowClear={true}
                  />
                );
              }
            },
          },
          {
            field: `locationInfo`,
            label: `详细地址`,
            component: 'Input',
            disabled: disabled,
            placeholder: '请输入',
            render: (text) => {
              if (disabled) {
                return <span style={{ paddingLeft: 8 }}>{text ? text : '--'}</span>;
              } else {
                return <Input placeholder="请输入" />;
              }
            },
          },
          {
            field: `applyFile`,
            label: `相关附件`,
            component: 'Render',
            required: false,
            placeholder: '请上传',
            render: (text, record) => {
              const fileName = 'applyFile';
              return (
                <>
                  {!disabled ? (
                    <UploadFormCommon
                      form={contractForm}
                      fileFormName={fileName}
                      spanCol={24}
                      inRowProportion={24}
                      name={'attachFile'}
                      required={false}
                      // accept={'.doc|.docx'}
                      url={'/assetInfo/uploadFile'}
                      downloadUrl={'/assetInfo/downloadFile'}
                      fileFormDelName={'delFile'}
                      delFunc={(delFilePath: string) => {
                        console.log('--- w文件url', delFilePath);
                      }}
                      // maxFile={1}
                      defaultFiles={text}
                      // hintTitle={'且只能上传 1 个！'}
                      fieldBusiPath={'assetFile'}
                    >
                      上传
                    </UploadFormCommon>
                  ) : (
                    <div
                      style={{
                        height: '100%',
                        display: 'flex',
                        alignItems: 'center',
                        marginLeft: '8px',
                      }}
                    >
                      {record?.[fileName]
                        ? splitFileUrl(record?.[fileName])?.map((e, i) => {
                            return (
                              <div>
                                <Tooltip title={e.attachName} key={new Date().getTime() * 25615265152 + e?.attachName}>
                                  <a
                                    onClick={() => {
                                      message.success('下载中，请稍后...');
                                      downloadTemplate('/assetInfo/downloadFile', e?.attachName, e?.attachUrl, () => {});
                                    }}
                                  >
                                    <MyIcon type="icon-file-text-fill" />
                                    &nbsp;
                                    {getFileNameNotType(e.attachName, 8)}
                                  </a>
                                </Tooltip>
                                {/* 轻阅读预览 */}
                                <Tooltip title={'在线预览'}>
                                  <Button type="link" size="small" onClick={() => onOpenReadOfdWord(e?.attachUrl)} icon={<EyeOutlined />} />
                                </Tooltip>
                              </div>
                            );
                          })
                        : '--'}
                    </div>
                  )}
                </>
              );
            },
          },
        ],
      },
      {
        key: 'accept-procurement',
        title: '材料明细',
        fieldCustomDom: <UpdateMaterielView openMaterialModalStatus={openMaterialModalStatus} pageType={pageType} />,
      },
      {
        key: 'accept-contract',
        title: (
          <>
            <span>
              {'资产价值相关的其他费用来源'}
              <p style={{ fontSize: 16, fontWeight: 400, color: 'red', margin: 0 }}>{`(提示：选择资产转化时相关的安装、调试、检测等服务合同)`}</p>
            </span>
          </>
        ),
        fieldCustomDom: <UpdateContractView handleSelectContract={handleSelectContract} pageType={pageType} contractForm={contractForm} />,
      },
    ],
  });

  return {
    config,
    methods,
  };
};

export { getUpdateConfig };
